import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { createRouter, createWebHistory } from 'vue-router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 引入全局样式系统
import './style.css'

import App from './App.vue'
import Home from './views/Home.vue'
import SoftwareSelection from './views/SoftwareSelection.vue'
import TemplateManagement from './views/TemplateManagement.vue'
import TemplateMarket from './views/TemplateMarket.vue'
import MyFavorites from './views/MyFavorites.vue'
import ScriptGeneration from './views/ScriptGeneration.vue'
import UserProfile from './views/UserProfile.vue'
import Notifications from './views/Notifications.vue'
import NotificationDetail from './views/NotificationDetail.vue'
import ComponentTest from './views/ComponentTest.vue'
import DialogStyleTest from './views/DialogStyleTest.vue'
import AvatarAuditManagement from './views/admin/AvatarAuditManagement.vue'

// 配置axios
axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL || '/api'
axios.defaults.timeout = 30000
axios.defaults.withCredentials = false

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
axios.interceptors.response.use(
  response => response,
  async error => {
    if (error.response?.status === 401) {
      // 401错误：清除认证状态

      // 清除本地存储
      localStorage.removeItem('token')

      // 清除用户store状态
      try {
        const { useUserStore } = await import('./stores/user')
        const userStore = useUserStore()
        userStore.logout()
      } catch (e) {
        console.error('清除用户状态失败:', e)
      }

      // 显示错误消息
      ElMessage.error('登录状态已过期，请重新登录')
    }
    return Promise.reject(error)
  }
)

// 路由配置
const routes = [
  { path: '/', name: 'Home', component: Home },
  { path: '/software', name: 'SoftwareSelection', component: SoftwareSelection },
  { path: '/template-market', name: 'TemplateMarket', component: TemplateMarket },
  { path: '/templates', name: 'TemplateManagement', component: TemplateManagement, meta: { requiresAuth: true } },
  { path: '/my-favorites', name: 'MyFavorites', component: MyFavorites, meta: { requiresAuth: true } },
  { path: '/script', name: 'ScriptGeneration', component: ScriptGeneration },
  { path: '/profile', name: 'UserProfile', component: UserProfile, meta: { requiresAuth: true } },
  { path: '/notifications', name: 'Notifications', component: Notifications, meta: { requiresAuth: true } },
  { path: '/notifications/:id', name: 'NotificationDetail', component: NotificationDetail, meta: { requiresAuth: true } },
  { path: '/admin/avatar-audit', name: 'AvatarAuditManagement', component: AvatarAuditManagement, meta: { requiresAuth: true, requiresAdmin: true } },
  { path: '/test', name: 'ComponentTest', component: ComponentTest },
  { path: '/dialog-test', name: 'DialogStyleTest', component: DialogStyleTest }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

const app = createApp(App)
const pinia = createPinia()

// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(pinia)

// 初始化用户状态
const initializeApp = async () => {
  const { useUserStore } = await import('./stores/user')
  const userStore = useUserStore()

  // 如果有token，尝试恢复用户状态
  if (userStore.token) {
    console.log('应用初始化：发现token，尝试恢复用户状态...')
    await userStore.initializeUserState()
  }
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 导入用户store（需要在pinia初始化后）
  const { useUserStore } = await import('./stores/user')
  const userStore = useUserStore()

  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 如果没有token，直接拒绝访问
    if (!userStore.token) {
      ElMessage.warning('请先登录后再访问该页面')
      next(false) // 阻止导航
      return
    }

    // 如果有token但没有用户信息，尝试获取用户信息
    if (!userStore.user) {
      try {
        console.log('路由守卫：尝试获取用户信息...')
        const result = await userStore.getCurrentUser()
        if (!result.success || !userStore.user) {
          console.log('路由守卫：获取用户信息失败，清除登录状态')
          userStore.logout()
          ElMessage.error('登录状态已过期，请重新登录')
          next(false)
          return
        }
        console.log('路由守卫：用户信息获取成功', userStore.user)
      } catch (error) {
        console.error('路由守卫：获取用户信息异常', error)
        userStore.logout()
        ElMessage.error('登录状态验证失败，请重新登录')
        next(false)
        return
      }
    }

    // 最终检查：确保用户已登录
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录后再访问该页面')
      next(false)
      return
    }
  }

  // 检查管理员权限
  if (to.meta.requiresAdmin) {
    // 必须先通过认证检查
    if (!userStore.isLoggedIn || !userStore.user) {
      ElMessage.warning('请先登录后再访问该页面')
      next(false)
      return
    }

    // 检查是否为管理员
    if (!userStore.user.role || (userStore.user.role !== 'ADMIN' && userStore.user.role !== 'SUPER_ADMIN')) {
      ElMessage.error('您没有权限访问此页面')
      next(false)
      return
    }
  }

  next() // 允许导航
})

app.use(router)
app.use(ElementPlus)

// 全局属性
app.config.globalProperties.$http = axios

// 初始化应用并挂载
initializeApp().then(() => {
  app.mount('#app')
  // 应用初始化完成
}).catch(error => {
  // 应用初始化失败，但仍需挂载应用
  app.mount('#app')
})
